﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Yuecai.Crypto;

namespace Yuecai.Storage
{
    /// <summary>
    /// 用于对普通文件的存储
    /// </summary>
    public class FileStorage
    {
        /// <summary>
        /// 创建一个文件并且写加密内容
        /// </summary>
        /// <param name="text">内容</param>
        /// <param name="path">文件路径</param>
        /// <param name="key">密码</param>
        /// <returns>是否成功</returns>
        public static bool Write(string text, string path, string key)
        {
            var fs = new FileStream(path, FileMode.Create);
            var buf = DesCrypto.Encrypt(text, key);
            fs.Write(buf, 0, buf.Length);
            fs.Close();
            return true;
        }

        /// <summary>
        /// 读取指定文件中的加密内容
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="key">密码</param>
        /// <returns>读到的内容</returns>
        public static string Read(string path, string key)
        {
            var fs = new FileStream(path, FileMode.Open);
            var buf = new byte[fs.Length];
            fs.Read(buf, 0, (int)fs.Length);
            fs.Close();
            return DesCrypto.Decrypt(buf, key);
        }

        /// <summary>
        /// 创建一个文件并且写内容
        /// </summary>
        /// <param name="text">内容</param>
        /// <param name="path">文件路径</param>
        /// <returns>是否成功</returns>
        public static bool WriteDirectly(string text, string path)
        {
            var fs = new FileStream(path, FileMode.Create);
            var buf = Encoding.Default.GetBytes(text);
            fs.Write(buf, 0, buf.Length);
            fs.Close();
            return true;
        }

        /// <summary>
        /// 读取指定文件中的内容
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns>读到的内容</returns>
        public static string ReadDirectly(string path)
        {
            var fs = new FileStream(path, FileMode.Open);
            var buf = new byte[fs.Length];
            fs.Read(buf, 0, (int)fs.Length);
            fs.Close();
            return Encoding.Default.GetString(buf);
        }
    }
}
